import { Component, OnInit } from '@angular/core';
import { NbAuthResult, NbAuthToken, NbLoginComponent } from '@nebular/auth';
import { Observable } from 'rxjs';
import { delay } from 'rxjs/operators';

interface LoginBody {
  key: string,
  pwd: string,
  for: string,
}

interface RememberUser {
  name: string,
  pwd: string,
  isRem?: boolean,
}

@Component({
  selector: 'ngx-login',
  templateUrl: './ngx-login.component.html'
})

export class NgxLoginComponent extends NbLoginComponent {

  user: LoginBody;

  rememberUser: RememberUser = {name: '', pwd: '', isRem: false};

  isRemember: boolean = false;

  ngOnInit(): void {
    this.user.for = 'AdminSystem';
  }

  getSorage(): void {
    // 选择记住我的用户再次输入用户名会自动填充密码
    const userList = JSON.parse(localStorage.getItem('userList')) || [];
    userList.forEach((item: RememberUser) => {
      if (item.name === this.user.key) {
        this.user.pwd = item.pwd;
        this.isRemember = item.isRem;
      }
    });
  }

  userStorge(key: string, pwd: string, isRem: boolean): void {
    let userList = JSON.parse(localStorage.getItem('userList')) || [];
    if (userList.length > 0) {
      // 只存储当前 localstorage 中没有的用户信息
      userList.forEach((item: RememberUser) => {
        if (item.name !== key) {
          this.storage(key, pwd, isRem, userList);
        }
      });
    } else {
      this.storage(key, pwd, isRem, userList);
    }
  }

  storage(key: string, pwd: string, isRem: boolean, userList): void {
    this.rememberUser.name = key;
    this.rememberUser.pwd = pwd;
    this.rememberUser.isRem = isRem;
    userList.push(this.rememberUser);
    localStorage.setItem('userList', JSON.stringify(userList));
  }

  // 取消记住我
  forgetMe(key: string, pwd: string, token): void {
    let userList = JSON.parse(localStorage.getItem('userList')) || [];
    userList.forEach((item: RememberUser, index: number) => {
      if (item.name === key) {
        userList.splice(index, 1);
      }
    })

    localStorage.setItem('userList', JSON.stringify(userList));
    sessionStorage.setItem('auth_app_token', JSON.stringify(token));
    localStorage.removeItem('auth_app_token');
  }

  // rRUt9u2e
  login(): void {
    this.service.authenticate('password', this.user)
        .pipe(
          delay(500)
        )
        .subscribe((authResult: NbAuthResult) => {
          console.log(authResult);
          if (authResult.isSuccess()) {
            const token = authResult.getToken();
            this.messages.push(...authResult.getMessages());
            // 记住用户，把用户的信息写入 localstorage
            if (this.isRemember) {
              this.userStorge(this.user.key, this.user.pwd, this.isRemember);
            } else {
              this.forgetMe(this.user.key, this.user.pwd, token);
            }
            this.router.navigate([authResult.getRedirect()]);
          } else {
            this.errors.push(...authResult.getErrors())
          }
        });
  }

}
